import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {BaseService} from "../../../shared/service/base.service";
import {ApiUrl} from "../../../config/api-url";
import {Router} from "@angular/router";

@Component({
  selector: 'app-bind-bank-card',
  templateUrl: './bind-bank-card.component.html',
  styleUrls: ['./bind-bank-card.component.less']
})
export class BindBankCardComponent implements OnInit {
  @Input()
  isVisible: any;
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  @Input()
  cardNoType: number;
  formModel: FormGroup;
  isOkLoading: boolean;

  constructor(private fb: FormBuilder, public baseService: BaseService, private router: Router) {
    this.buildForm();
  }

  ngOnInit(): void {

  }

  buildForm() {
    this.formModel = this.fb.group({
      type: ['', [Validators.required]],
      bankName: ['', [Validators.required]],
      branchName: ['', [Validators.required]],
      bankCardNo: ['', [Validators.required]],
      bankCertName: ['', [Validators.required]],
    });
  }

  ngOnChanges() {
    if (this.cardNoType == 2) {
      this.formModel.get('type').setValue('2');
    } else {
      this.formModel.get('type').setValue('1');
    }
  }


  handleCancel() {
    this.isVisible = false;
    this.emit.emit(this.isVisible);
  }

  handleOk() {
    this.isOkLoading = true;
    for (const i in this.formModel.controls) {
      if (!this.formModel.controls[i].valid) {
        this.isOkLoading = false;
      }
      this.formModel.controls[i].markAsDirty();
      this.formModel.controls[i].updateValueAndValidity();
    }

    if (!this.isOkLoading) {
      return;
    }
    this.baseService.layer.modalConfirm("是否确定", confirm => {
      if (confirm) {
        this.baseService.post(ApiUrl.UserBankCardUrl, this.formModel.value).subscribe(data => {
          if (data.status == 0) {
            this.isOkLoading = false;
            this.handleCancel();
          } else {
            this.isOkLoading = false;
            this.baseService.layer.messageError(data.msg);
          }
        });
      }
    });

  }
}
